#!/usr/bin/env python
# -*- coding: utf-8 -*-


# ----------------------
# TODO:
# * progress bar
# * multiprocess download
# * params handle
# ----------------------

import sys
import argparse
import ConfigParser
import socket


def parse_firmware_list(ini='config.ini'):
    cf = ConfigParser.ConfigParser()
    cf.read(ini)
    fm_list = {}
    dev_ip_list = cf.options('ip_fm_list')
    for ip in dev_ip_list:
        fm_list[ip] = cf.get('ip_fm_list', ip)

    return fm_list


def send_bin_file(dev_ip, bin_file):
    with open(bin_file, 'rb') as bin_file:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((dev_ip, 23))
        rsp = sock.recv(1024)
        #print rsp
        for i in range(0, 5):
            sock.sendall('update\r\n')
            rsp = sock.recv(32)
            if 'ready\r\n' == rsp:
                while True:
                    send_block = bin_file.read(256)
                    if not send_block:
                        break
                    sock.sendall(send_block)
                sock.close()
                return True
        return False


def main(args):
    if args.config:
        download_list = parse_firmware_list(args.config)
        print '[DOWNLOAD LIST]'
        for ip in download_list:
            print '\t[+]' + ip + ': ' + download_list[ip]
            if send_bin_file(ip, download_list[ip]):
                print '\t[-]' + ip + ': ' + download_list[ip] + ' FAILED'
        return

    if not (args.device and args.bin):
        print 'parameters error'
        return

    print '[+]' + args.device + ': ' + args.bin
    if send_bin_file(args.device, args.bin):
        print '[+]Update ' + args.device + ' DONE, waiting for reboot...'


if __name__ == "__main__":
    parser = argparse.ArgumentParser(prog='python ' + sys.argv[0])
    parser.add_argument('-d', '--device', help='Device IP address')
    parser.add_argument('-b', '--bin', help='Firware binary file to be downloaded')
    parser.add_argument('-c', '--config', help='Indicate ini file path')
    args = parser.parse_args()

    main(args)
